package transgui;

import java.util.LinkedList;

import javax.swing.ListModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;

import libraries.LibraryContainer;
import libraries.TransPart;
import libraries.TransPartLibrary;

/**
 * essentially the same as a LibraryContainer, but implements a ListModel, so listener functionality is added; newLib creates a TransPartLibraryList rather than a TransPartLibrary
 */
public class LibraryContainerList extends LibraryContainer implements ListModel<TransPartLibrary> {

	private LinkedList<ListDataListener> listeners;
	
	private LinkedList<TransPartLibraryList> libraries;
	
	public LibraryContainerList() {
		super();
		listeners = new LinkedList<ListDataListener>();
	}

	@Override
	public void addListDataListener(ListDataListener listener) {
		listeners.add(listener);
	}

	@Override
	public TransPartLibrary getElementAt(int n) {
		return this.getLibraries().get(n);
	}

	@Override
	public int getSize() {
		return this.getLibraries().size();
	}
	
	@Override
	public String addPart(TransPartLibraryList lib, TransPart part) {
		String result = super.addPart(lib, part);
		if(result.equals("")) {
			ListDataEvent e = new ListDataEvent(lib, ListDataEvent.INTERVAL_ADDED, lib.getSize()-1, lib.getSize()-1);
			for (ListDataListener l: lib.getListeners()) {
				l.intervalAdded(e);
			}
		}
		return result;
	}
	
	@Override
	public void removeListDataListener(ListDataListener listener) {
		listeners.remove(listener);
		
	}
	
	@Override
	public String addLibrary (TransPartLibrary lib) {
		String s = super.addLibrary(lib);
		if(s.equals("")){
			ListDataEvent e = new ListDataEvent(this, ListDataEvent.INTERVAL_ADDED, getLibraries().size()-1, getLibraries().size()-1);
			for (ListDataListener l: listeners) {
				l.intervalAdded(e);
			}
		}
		return s;
	}
	
	@Override
	public void deleteLibrary(TransPartLibrary lib) {
		int i = getLibraries().indexOf(lib);
		super.deleteLibrary(lib);
		ListDataEvent e = new ListDataEvent(this, ListDataEvent.INTERVAL_REMOVED, i, i);
		for (ListDataListener l: listeners) {
			l.intervalRemoved(e);
		}
	}
	
	@Override
	protected TransPartLibrary newLib(String name) {
		return new TransPartLibraryList(name);
	}

	public static LibraryContainerList testLibraryContainer() {
		LibraryContainerList libCon = new LibraryContainerList();
		libCon.addLibrary(TransPartLibraryList.testLibrary());
		
		return libCon;
	}

}
